﻿<%@ WebHandler Language="C#" Class="AjaxFileupload" %>

using System;
using System.IO;
using System.Web;
using Business.Common;
using Business.Model.WebUploader;
using System.Linq;

public class AjaxFileupload : IHttpHandler
{
    #region 文件分片
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        //上传目录
        var uploadDirectory = context.Request.Form["uploadDirectory"];
        //如果进行了分片
        if (context.Request.Form.AllKeys.Contains("chunk"))
        {
            //当前分片在上传分片中的顺序（从0开始）
            var chunk = Convert.ToInt32(context.Request.Form["chunk"]);
            //根据GUID创建用该GUID命名的临时文件夹 
            var folder = context.Server.MapPath(string.Concat("~/", uploadDirectory, "/", context.Request["guid"], "/"));
            var path = folder + chunk;
            //建立临时传输文件夹
            if (!Directory.Exists(Path.GetDirectoryName(folder)))
            {
                Directory.CreateDirectory(folder);
            }
            if (File.Exists(path)) { File.Delete(path); }
            var file = context.Request.Files[0];
            using (var addFile = new FileStream(path, FileMode.Append, FileAccess.Write))
            {
                using (var addWriter = new BinaryWriter(addFile))
                {
                    //获得上传的分片数据流
                    using (var stream = file.InputStream)
                    {
                        using (var tempReader = new BinaryReader(stream))
                        {
                            //将上传的分片追加到临时文件末尾
                            addWriter.Write(tempReader.ReadBytes((int)stream.Length));
                        }
                    }
                }
            }
            var result = new ChunkedResult
            {
                chunked = true,
                hasError = false,
                f_ext = Path.GetExtension(file.FileName)
            };
            context.Response.Write(result.T2Json());
        }
        else//没有分片直接保存
        {
            var folder = context.Server.MapPath(string.Concat("~/", uploadDirectory, "/"));
            if (!Directory.Exists(Path.GetDirectoryName(folder)))
            {
                Directory.CreateDirectory(folder);
            }
            context.Request.Files[0].SaveAs(context.Server.MapPath(string.Concat("~/", uploadDirectory, "/", DateTime.Now.ToFileTime(), Path.GetExtension(context.Request.Files[0].FileName))));
            var result = new ChunkedResult
            {
                chunked = false,
                hasError = false
            };
            context.Response.Write(result.T2Json());
        }
    }
    #endregion

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}